#include <REGX52.H>
#include <INTRINS.H>
#include <STRING.H>
#include "delay.h"
#include "lcd1602.h"
#include "matrix.h"

#define PASSWD_MAX_LEN 6

unsigned char pwdArry[PASSWD_MAX_LEN+1];
unsigned char count = 0;
unsigned char pwdPre[PASSWD_MAX_LEN+1] = "412633";

void passwdInit()
{
	unsigned char i = 0;
	
	for(i=0; i<= PASSWD_MAX_LEN; i++)
	{
		pwdArry[i] = '\0';
	}
}

void passwdShow()
{
	unsigned char i = 0;
	
	
	for(i=1; i<= PASSWD_MAX_LEN; i++)
	{
		LCD_ShowChar(2, i, ' ');
	}
	
	i = 0;
	while(i < count)
	{
		LCD_ShowChar(2, PASSWD_MAX_LEN-i, pwdArry[count-i-1]);
		i++;
	}
}

void passwdShowClean()
{
	unsigned char i = 0;
	
	while(i < PASSWD_MAX_LEN)
	{
		LCD_ShowChar(2, i+1, ' ');
		i++;
	}
}
void main()
{
	unsigned char keyNum = 0;
	unsigned int password = 0;
	

	passwdInit();

	
	LCD_Init();
	LCD_ShowString(1, 1, "Password:");
	
	while(1)
	{
		keyNum = MatrixKey();
		
		if(keyNum && keyNum <= 10)						//S1~S10按键按下，输入密码
		{
			if(count < PASSWD_MAX_LEN ){								//如果输入次数小于4才更新password
				password *= 10;							//密码左移1位
				password += keyNum % 10;				//获取1位密码，对10取余把10转换为0
				
				pwdArry[count] = keyNum % 10 + 0x30;
				count++;
			}
			
			//LCD_ShowNum(2, 1, password, 4);				//更新显示密码
			passwdShow();
			LCD_ShowString(1, 13, "    ");				//更新显示密码状态
		}
		
		if(keyNum){
			if(keyNum == 11)								//KeyNUm=11定义为'确认'按键
			{
				if(strcmp(pwdPre, pwdArry) == 0)
				{
					LCD_ShowString(1, 13, "OK! ");
					count = 0;
					password = 0;
					//LCD_ShowString(2, 1, "    ");
				}
				else{
					LCD_ShowString(1, 13, "ERR!");
					count = 0;
					password = 0;
					//LCD_ShowString(2, 1, "    ");
				}
			}
			
			if(keyNum == 12)							//KeyNUm=12定义为'取消'按键
			{
				LCD_ShowString(1, 13, "    ");			//更新显示密码状态
				count = 0;
				password = 0;
				LCD_ShowString(2, 1,  "    ");			//更新密码显示
				
				
				
				passwdInit();							//密码初始化
				passwdShowClean();						//更新密码显示
			}
			
			if(keyNum == 13)							//KeyNUm=13定义为'删除'按键
			{
				LCD_ShowString(1, 13, "    ");
				if(count){
					pwdArry[count-1] = '\0';
					count--;
				}
				password /= 10;							//更新密码，'删除'键每次更新密码
				//LCD_ShowNum(2, 1, password, 4);		//更新显示密码
				passwdShow();							//更新显示密码	
			}
		}
	}
}
